package rs.udd.service;

import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import rs.udd.model.Advert;
import rs.udd.model.Agent;
import rs.udd.model.AgentAdvertApplication;
import rs.udd.repository.AdvertRepository;
import rs.udd.repository.AgentAdvertApplicationRepository;
import rs.udd.repository.AgentRepository;
import rs.udd.service.dto.advert.ApplyAdvertDto;
import rs.udd.service.util.SecurityUtil;

@Service
@Transactional
public class ApplyAdvertServiceImpl implements ApplyAdvertService {
	
	private static final Logger LOGGER = LogManager.getLogger(ApplyAdvertServiceImpl.class);
	
	@Resource
	private AdvertRepository advertRepository;

	@Resource
	private AgentRepository agentRepository;
	
	@Resource
	private MailService mailService;
	
	@Resource
	private AgentAdvertApplicationRepository agentAdvertContactRepository;
	
	@Override
	public void apply(Long advertId, ApplyAdvertDto applyAdvertDto) {
		Advert advert = advertRepository.findOne(advertId);
		Agent loggedAgent = SecurityUtil.getLoggedUser(Agent.class);
		loggedAgent = agentRepository.findOne(loggedAgent.getId());
		
		AgentAdvertApplication application = new AgentAdvertApplication();
		application.setAdvert(advert);
		application.setAgent(loggedAgent);
		application.setMessage(applyAdvertDto.getMessage());
		agentAdvertContactRepository.save(application);
		advertRepository.save(advert);
		agentRepository.save(loggedAgent);
		
		LOGGER.info("Agent '" + loggedAgent.getUsername() + "' applied for advert '" + advert.getTitle() + "'");
		
		String sendEmailTo = advert.getAdvertiser().getEmail();
		String subject = "Application for your " + advert.getTitle();
		String body = "Agent " + loggedAgent.getFirstname() + " " + loggedAgent.getLastname() + 
				" applied for your advert " + advert.getTitle();
		body += "\nMessage from agent:\n" + applyAdvertDto.getMessage();
		mailService.sendMail(sendEmailTo, subject, body);
	}

	@Override
	public boolean checkIfAgentApplied(Long advertId) {
		boolean agentIsLogged = SecurityUtil.checkLoggedRole(Agent.class);
		if (agentIsLogged) {
			Advert advert = advertRepository.findOne(advertId);
			Agent agent = SecurityUtil.getLoggedUser(Agent.class);
			agent = agentRepository.findOne(agent.getId());
			AgentAdvertApplication advertApplication = agentAdvertContactRepository.findByAgentAndAdvert(agent, advert);
			boolean applied = agent.getApplicationsForAdvert().contains(advertApplication);
			
			return applied;
		} else {
			return false;
		}
	} 

}
